﻿#include "algorithmparammanager.h"
#include "dataform.h"
#include "ui_dataform.h"
#include <QGraphicsDropShadowEffect>
#include <QListView>
#include <QMessageBox>
#include <QDate>
#include <QFileDialog>
#include <QDesktopServices>
#include <QProgressDialog>

DataForm::DataForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DataForm)
{
    ui->setupUi(this);


    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setWindowModality(Qt::ApplicationModal);
    initWindow();

    // 设置日期范围，默认最近7天
    QDate currentDate = QDate::currentDate();
    ui->dateStart->setDate(currentDate.addDays(-7));
    ui->dateEnd->setDate(currentDate);

    m_nCurPage = 1;
    m_nRowsPerPage = 10;
    m_nTotalPages = 1;

    ui->Bt_Search->setEnabled(false);
    ui->Bt_Delete->setEnabled(false);
    m_nCurID = -1;

    connect(ui->tableWidget->verticalScrollBar(), SIGNAL(valueChanged(int)),
            this, SLOT(OnSlideAction(int)));

    // 样式设置
    QFile file(":/qss/dlg.qss");
    if (file.open(QFile::ReadOnly)) {
        QTextStream filetext(&file);
        QString stylesheet = filetext.readAll();
        this->setStyleSheet(stylesheet);
        file.close();
    }

    // 阴影效果
    QGraphicsDropShadowEffect *shadow_effectA = new QGraphicsDropShadowEffect(this);
    QGraphicsDropShadowEffect *shadow_effectB = new QGraphicsDropShadowEffect(this);
    QGraphicsDropShadowEffect *shadow_effectC = new QGraphicsDropShadowEffect(this);

    shadow_effectA->setOffset(0, 0);
    shadow_effectA->setColor(QColor(150,150,150));
    shadow_effectA->setBlurRadius(6);

    shadow_effectB->setOffset(0, 0);
    shadow_effectB->setColor(QColor(150,150,150));
    shadow_effectB->setBlurRadius(6);

    shadow_effectC->setOffset(0, 0);
    shadow_effectC->setColor(QColor(150,150,150));
    shadow_effectC->setBlurRadius(6);

    ui->Data_gBox_1->setGraphicsEffect(shadow_effectA);
    ui->Data_gBox_2->setGraphicsEffect(shadow_effectB);
    ui->Data_gBox_3->setGraphicsEffect(shadow_effectC);


    m_sql.init("welding_db");
    // 初始加载数据
    updateWeldingData();
}

DataForm::~DataForm()
{
    delete ui;
}

void DataForm::initWindow()
{
    // 表格设置
    ui->tableWidget->setShowGrid(true);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->verticalHeader()->hide();
    InThresholdParam param = AlgorithmParamManager::instance()->getAlgParam();
    // 设置表格列（焊锡检测结果）
    QStringList header;
    header  << tr("id")
            << tr("hxPort")
            << tr("hxId")
            << tr("Weight(%1~%2mm)").arg(param.min_w).arg(param.max_w)
            << tr("Height(%1~%2mm)").arg(param.min_h).arg(param.max_h)
            << tr("Area(%1~%2mm²)").arg(param.min_area).arg(param.max_area)
            << tr("TBtoHX(%1~%2mm)").arg(param.min_TBDis).arg(param.max_TBDis)
            << tr("Offset(0~%1mm)").arg(param.max_PY)
            << tr("LTsum(0~%1mm²)").arg(param.LT_ALLArea_max)
            << tr("LTmax(0~%1mm²)").arg(param.LT_MAXArea_max)
            << tr("HDsum(0~%1mm²)").arg(param.HD_ALLArea_max)
            << tr("HDmax(0~%1mm²)").arg(param.HD_MAXArea_max)
            << tr("hxReult")
            << tr("hxReultsDescribe")
            << tr("changeTime");
    ui->tableWidget->setColumnCount(header.size());
    ui->tableWidget->setHorizontalHeaderLabels(header);

    /* 关键：让列宽根据内容自适应，并允许用户拖动 */
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    /* 如果想再紧一点，可以限制最小宽度 */
    for (int c = 0; c < header.size(); ++c)
        ui->tableWidget->horizontalHeader()->setMinimumSectionSize(80);
}

void DataForm::setWeldingDataPage()
{
    updateWeldingData();
}

void DataForm::updateWeldingData()
{


    QDateTime startTime = QDateTime(ui->dateStart->date(), QTime(0, 0, 0));
    QDateTime endTime = QDateTime(ui->dateEnd->date(), QTime(23, 59, 59));

    m_currentResults = m_sql.queryWeldingResultsByTimeRange(startTime, endTime);

    ui->tableWidget->clearContents();

    // 计算分页
    if(m_currentResults.size() % m_nRowsPerPage == 0) {
        m_nTotalPages = m_currentResults.size() / m_nRowsPerPage;
    } else {
        m_nTotalPages = m_currentResults.size() / m_nRowsPerPage + 1;
    }

    if (m_nTotalPages == 0) m_nTotalPages = 1;

    ui->labPage->setText(QString("%1/%2").arg(m_nCurPage).arg(m_nTotalPages));

    // 计算当前页显示的数据范围
    int startIndex = (m_nCurPage - 1) * m_nRowsPerPage;
    int endIndex = qMin(startIndex + m_nRowsPerPage, m_currentResults.size());

    ui->tableWidget->setRowCount(endIndex - startIndex);

    // 统计信息
    int totalCount = m_currentResults.size();
    int okCount = 0;
    int ngCount = 0;

    for (const auto& result : m_currentResults) {
        if (result.hxReult) {
            okCount++;
        } else {
            ngCount++;
        }
    }

    // 更新统计标签
    ui->data_number->setText(QString::number(totalCount));
    ui->data_weight->setText(QString::number(okCount));
    ui->data_ng_value->setText(QString::number(ngCount));

    for(int i = startIndex; i < endIndex; i++) {
        int row = i - startIndex;
        const DB_WeldingResult& result = m_currentResults[i];

        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(result.id)));
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(result.hxPort));
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem(QString::number(result.hxId)));
        ui->tableWidget->setItem(row, 3, new QTableWidgetItem(QString::number(result.hxWeight, 'f', 2)));
        ui->tableWidget->setItem(row, 4, new QTableWidgetItem(QString::number(result.hxHeight, 'f', 2)));
        ui->tableWidget->setItem(row, 5, new QTableWidgetItem(QString::number(result.hxArea, 'f', 3)));
        ui->tableWidget->setItem(row, 6, new QTableWidgetItem(QString::number(result.hxDistance, 'f', 2)));
        ui->tableWidget->setItem(row, 7, new QTableWidgetItem(QString::number(result.hxPianyi, 'f', 2)));
        ui->tableWidget->setItem(row, 8, new QTableWidgetItem(QString::number(result.hxLTSumArea, 'f', 2)));
        ui->tableWidget->setItem(row, 9, new QTableWidgetItem(QString::number(result.hxLTMaxArea, 'f', 2)));
        ui->tableWidget->setItem(row, 10, new QTableWidgetItem(QString::number(result.hxHDSumArea, 'f', 2)));
        ui->tableWidget->setItem(row, 11, new QTableWidgetItem(QString::number(result.hxHDMaxArea, 'f', 2)));
        ui->tableWidget->setItem(row, 12, new QTableWidgetItem(result.hxReult ? tr("OK") : tr("NG")));
        ui->tableWidget->setItem(row, 13, new QTableWidgetItem(result.hxReultsDescribe));
        ui->tableWidget->setItem(row, 14, new QTableWidgetItem(result.changeTime));

        // 设置文本居中
        for(int j = 0; j < ui->tableWidget->columnCount(); j++) {
            if (ui->tableWidget->item(row, j)) {
                ui->tableWidget->item(row, j)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            }
        }

        // 根据检测结果设置行颜色
        if (!result.hxReult) {
            for(int j = 0; j < ui->tableWidget->columnCount(); j++) {
                if (ui->tableWidget->item(row, j)) {
                    ui->tableWidget->item(row, j)->setBackground(QColor(255, 200, 200)); // NG显示为浅红色
                }
            }
        }
    }
}

void DataForm::OnSlideAction(int nRowIndex)
{
    ++nRowIndex;
    if (nRowIndex % m_nRowsPerPage == 0) {
        m_nCurPage = nRowIndex / m_nRowsPerPage;
    } else {
        m_nCurPage = nRowIndex / m_nRowsPerPage + 1;
    }
    ui->labPage->setText(QString("%1/%2").arg(m_nCurPage).arg(m_nTotalPages));
}

void DataForm::on_Bt_PrePage_clicked()
{
    m_nCurPage--;
    if(m_nCurPage <= 0){
        m_nCurPage = m_nTotalPages;
    }
    updateWeldingData();
}

void DataForm::on_Bt_NextPage_clicked()
{
    m_nCurPage++;
    if (m_nCurPage > m_nTotalPages) {
        m_nCurPage = 1;
    }
    updateWeldingData();
}

void DataForm::on_Bt_Delete_clicked()
{
    if (m_nCurID == -1) {
        QMessageBox::warning(this, tr("警告"), tr("请选择要删除的记录"));
        return;
    }

    if (QMessageBox::question(this, tr("删除"), tr("确定要删除这条记录吗？"),
                              QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
        if (m_sql.deleteWeldingResult(m_nCurID)) {
            QMessageBox::information(this, tr("成功"), tr("记录删除成功"));
            updateWeldingData();
            m_nCurID = -1;
            ui->Bt_Delete->setEnabled(false);
            ui->Bt_Search->setEnabled(false);
        } else {
            QMessageBox::warning(this, tr("错误"), tr("删除记录失败"));
        }
    }
}

void DataForm::on_Bt_Query_clicked()
{
    m_nCurPage = 1;
    updateWeldingData();
}

void DataForm::on_tableWidget_cellClicked(int row, int column)
{
    column = 0;
    if(m_nCurID > 0){
        ui->Bt_Delete->setEnabled(true);
        ui->Bt_Search->setEnabled(true);
    }
    QTableWidgetItem* item = ui->tableWidget->item(row ,0);
    m_nCurID = item->text().toInt();
}

void DataForm::on_Bt_Confirm_clicked()
{
    if (m_nCurID != -1) {
        emit sendBatchInfo(m_nCurID);
    }
    this->close();
}

void DataForm::on_Bt_Return_clicked()
{
    this->close();
}

void DataForm::on_tableWidget_cellDoubleClicked(int row, int column)
{
    on_Bt_Search_clicked();
}

void DataForm::on_Bt_Search_clicked()
{
    if (m_nCurID == -1) {
        QMessageBox::warning(this, tr("警告"), tr("请选择要查看的记录"));
        return;
    }

    // 查找选中的记录
    for (const auto& result : m_currentResults) {
        if (result.id == m_nCurID) {
            // 获取算法参数用于显示阈值范围
            InThresholdParam param = AlgorithmParamManager::instance()->getAlgParam();

            QString detail = QString(
                                 "═══════════════════════════════════════════\n"
                                 "             焊锡检测记录详情\n"
                                 "═══════════════════════════════════════════\n\n"
                                 "【基本信息】\n"
                                 "  端口编号: %1\n"
                                 "  焊锡编号: %2\n"
                                 "  批次编号: %3\n\n"
                                 "【尺寸检测】\n"
                                 "  焊锡长度: %4 mm (标准: %5~%6mm)\n"
                                 "  焊锡宽度: %7 mm (标准: %8~%9mm)\n"
                                 "  瑕疵面积: %10 mm² (标准: %11~%12mm²)\n\n"
                                 "【位置检测】\n"
                                 "  裸露铜引脚长度: %13 mm (标准: %14~%15mm)\n"
                                 "  焊锡偏移: %16 mm (标准: 0~%17mm)\n\n"
                                 "【瑕疵检测】\n"
                                 "  漏铜总面积: %18 mm² (标准: 0~%19mm²)\n"
                                 "  漏铜最大面积: %20 mm² (标准: 0~%21mm²)\n"
                                 "  黑点总面积: %22 mm² (标准: 0~%23mm²)\n"
                                 "  黑点最大面积: %24 mm² (标准: 0~%25mm²)\n\n"
                                 "【检测结果】\n"
                                 "  最终判定: %26\n"
                                 "  结果说明: %27\n\n"
                                 "【时间信息】\n"
                                 "  创建时间: %28\n"
                                 "  修改时间: %29\n"
                                 "═══════════════════════════════════════════")
                                 .arg(result.hxPort)
                                 .arg(result.hxId)
                                 .arg(result.hxBatch)

                                 // 尺寸检测
                                 .arg(result.hxWeight, 0, 'f', 2)
                                 .arg(param.min_w, 0, 'f', 1).arg(param.max_w, 0, 'f', 1)
                                 .arg(result.hxHeight, 0, 'f', 2)
                                 .arg(param.min_h, 0, 'f', 1).arg(param.max_h, 0, 'f', 1)
                                 .arg(result.hxArea, 0, 'f', 3)
                                 .arg(param.min_area, 0, 'f', 1).arg(param.max_area, 0, 'f', 1)

                                 // 位置检测
                                 .arg(result.hxDistance, 0, 'f', 2)
                                 .arg(param.min_TBDis, 0, 'f', 2).arg(param.max_TBDis, 0, 'f', 1)
                                 .arg(result.hxPianyi, 0, 'f', 2)
                                 .arg(param.max_PY, 0, 'f', 1)

                                 // 瑕疵检测
                                 .arg(result.hxLTSumArea, 0, 'f', 3)
                                 .arg(param.LT_ALLArea_max, 0, 'f', 2)
                                 .arg(result.hxLTMaxArea, 0, 'f', 3)
                                 .arg(param.LT_MAXArea_max, 0, 'f', 2)
                                 .arg(result.hxHDSumArea, 0, 'f', 3)
                                 .arg(param.HD_ALLArea_max, 0, 'f', 1)
                                 .arg(result.hxHDMaxArea, 0, 'f', 3)
                                 .arg(param.HD_MAXArea_max, 0, 'f', 1)

                                 // 检测结果
                                 .arg(result.hxReult ? "✅ 合格(OK)" : "❌ 不合格(NG)")
                                 .arg(result.hxReultsDescribe.isEmpty() ? "无" : result.hxReultsDescribe)

                                 // 时间信息
                                 .arg(result.createTime)
                                 .arg(result.changeTime);

            // 创建详细信息的对话框
            QMessageBox msgBox(this);
            msgBox.setWindowTitle(tr("焊锡检测记录详情"));
            msgBox.setText(detail);
            msgBox.setIcon(QMessageBox::Information);
            msgBox.setStandardButtons(QMessageBox::Ok);

            // 设置对话框大小
            msgBox.setMinimumWidth(500);

            msgBox.exec();
            break;
        }
    }
}

void DataForm::on_Bt_Export_clicked()
{
    // 检查是否有数据可以导出
    if (m_currentResults.isEmpty()) {
        QMessageBox::warning(this, tr("警告"), tr("没有数据可以导出！"));
        return;
    }

    // 打开文件保存对话框
    QString fileName = QFileDialog::getSaveFileName(
        this,
        tr("导出Excel文件"),
        QDir::homePath() + "/焊锡检测数据_" + QDate::currentDate().toString("yyyyMMdd"),
        tr("Excel文件 (*.xlsx)")
        );

    if (fileName.isEmpty()) {
        return;
    }

    // 确保文件扩展名
    if (!fileName.endsWith(".xlsx", Qt::CaseInsensitive)) {
        fileName += ".xlsx";
    }

    // 创建进度对话框
    QProgressDialog progress(tr("正在导出数据..."), tr("取消"), 0, m_currentResults.size(), this);
    progress.setWindowModality(Qt::WindowModal);
    progress.show();

    try {
        // 创建Excel应用程序对象
        QAxObject *excel = new QAxObject("Excel.Application");
        if (excel->isNull()) {
            QMessageBox::critical(this, tr("错误"), tr("无法创建Excel对象！\n请确保已安装Microsoft Excel。"));
            delete excel;
            return;
        }

        excel->setProperty("Visible", false);
        excel->setProperty("DisplayAlerts", false);

        // 获取工作簿集合
        QAxObject *workbooks = excel->querySubObject("Workbooks");
        QAxObject *workbook = workbooks->querySubObject("Add");
        QAxObject *worksheets = workbook->querySubObject("Worksheets");
        QAxObject *worksheet = worksheets->querySubObject("Item(int)", 1);

        // 设置表头
        QStringList headers;
        headers << "ID" << "端口编号" << "焊锡编号" << "焊锡长度(mm)" << "焊锡宽度(mm)"
                << "焊锡面积(mm²)" << "裸露铜引脚长度(mm)" << "焊锡偏移(mm)"
                << "漏铜总面积(mm²)" << "漏铜最大面积(mm²)"
                << "黑点总面积(mm²)" << "黑点最大面积(mm²)"
                << "检测结果" << "结果说明" << "修改时间";

        // 写入表头
        for (int col = 0; col < headers.size(); ++col) {
            QAxObject *cell = worksheet->querySubObject("Cells(int,int)", 1, col + 1);
            cell->setProperty("Value", headers[col]);

            // 设置表头样式
            QAxObject *font = cell->querySubObject("Font");
            font->setProperty("Bold", true);
            font->setProperty("Size", 10);

            // 设置对齐方式 - 使用正确的方法
            cell->setProperty("HorizontalAlignment", -4108);  // xlCenter
            cell->setProperty("VerticalAlignment", -4108);    // xlCenter

            delete cell;
        }

        // 获取算法参数用于显示阈值范围
        InThresholdParam param = AlgorithmParamManager::instance()->getAlgParam();

        // 写入数据
        for (int row = 0; row < m_currentResults.size(); ++row) {
            // 更新进度
            progress.setValue(row);
            if (progress.wasCanceled()) {
                break;
            }

            QApplication::processEvents(); // 处理事件，避免界面冻结

            const DB_WeldingResult &result = m_currentResults[row];
            int excelRow = row + 2;  // Excel行号从1开始，表头占第1行

            // 写入数据
            writeCellValue(worksheet, excelRow, 1, result.id, !result.hxReult);
            writeCellValue(worksheet, excelRow, 2, result.hxPort, !result.hxReult);
            writeCellValue(worksheet, excelRow, 3, result.hxId, !result.hxReult);
            writeCellValue(worksheet, excelRow, 4, QString::number(result.hxWeight, 'f', 2), !result.hxReult);
            writeCellValue(worksheet, excelRow, 5, QString::number(result.hxHeight, 'f', 2), !result.hxReult);
            writeCellValue(worksheet, excelRow, 6, QString::number(result.hxArea, 'f', 3), !result.hxReult);
            writeCellValue(worksheet, excelRow, 7, QString::number(result.hxDistance, 'f', 2), !result.hxReult);
            writeCellValue(worksheet, excelRow, 8, QString::number(result.hxPianyi, 'f', 2), !result.hxReult);
            writeCellValue(worksheet, excelRow, 9, QString::number(result.hxLTSumArea, 'f', 3), !result.hxReult);
            writeCellValue(worksheet, excelRow, 10, QString::number(result.hxLTMaxArea, 'f', 3), !result.hxReult);
            writeCellValue(worksheet, excelRow, 11, QString::number(result.hxHDSumArea, 'f', 3), !result.hxReult);
            writeCellValue(worksheet, excelRow, 12, QString::number(result.hxHDMaxArea, 'f', 3), !result.hxReult);
            writeCellValue(worksheet, excelRow, 13, result.hxReult ? "OK" : "NG", !result.hxReult);
            writeCellValue(worksheet, excelRow, 14, result.hxReultsDescribe, !result.hxReult);
            writeCellValue(worksheet, excelRow, 15, result.changeTime, !result.hxReult);
        }

        progress.setValue(m_currentResults.size());

        // 自动调整列宽
        QAxObject *usedRange = worksheet->querySubObject("UsedRange");
        QAxObject *columns = usedRange->querySubObject("Columns");
        columns->dynamicCall("AutoFit()");

        // 保存文件
        workbook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(fileName));
        workbook->dynamicCall("Close()");
        excel->dynamicCall("Quit()");

        // 清理对象
        delete worksheet;
        delete worksheets;
        delete workbook;
        delete workbooks;
        delete excel;

        if (!progress.wasCanceled()) {
            QMessageBox::information(this, tr("成功"),
                                     tr("数据已成功导出到：\n%1").arg(fileName));

            // 可选：打开导出的文件
            if (QMessageBox::question(this, tr("打开文件"),
                                      tr("是否打开导出的Excel文件？"),
                                      QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
                QDesktopServices::openUrl(QUrl::fromLocalFile(fileName));
            }
        }

    } catch (...) {
        QMessageBox::critical(this, tr("错误"), tr("导出Excel文件失败！\n请确保已安装Microsoft Excel。"));
    }
}

// 辅助函数：设置单元格值和样式
void DataForm::writeCellValue(QAxObject *worksheet, int row, int col, const QVariant &value, bool isNG)
{
    QAxObject *cell = worksheet->querySubObject("Cells(int,int)", row, col);
    cell->setProperty("Value", value);

    // 设置文本居中
    cell->setProperty("HorizontalAlignment", -4108);  // xlCenter
    cell->setProperty("VerticalAlignment", -4108);    // xlCenter

    // 如果是NG数据，设置红色背景
    if (isNG) {
        QAxObject *interior = cell->querySubObject("Interior");
        interior->setProperty("Color", QColor(255, 200, 200));
        delete interior;
    }

    delete cell;
}
